'use strict';

/* Controllers */

// angular.module('myApp.controllers', [])
//   .controller('MyCtrl1', ['$scope', function($scope) {

//   }])
//   .controller('MyCtrl2', ['$scope', function($scope) {

//   }]);

var __scope = null;
var __page = 1;

var myControllers = angular.module('myApp.controllers', []);

myControllers.controller('BookListCtrl', [
    '$scope', '$routeParams', '$location', '$http',
    function ($scope, $routeParams, $location, $http) {
        var tag = 'rock';
        var count = 10;
        __page = parseInt($routeParams.page) || 1;

        __scope = $scope;
        __scope.prevPage = function () {
            __page = (__page > 1) ? --__page : 1;
            $location.path('/book-list/' + __page);
        };
        __scope.nextPage = function () {
            __page = ++__page;
            $location.path('/book-list/' + __page);
        };

        var apiUri = 'https://api.douban.com/v2/book/search';
        var params = {
            callback: 'bookListCallback',
            tag: tag,
            start: count * (__page - 1),
            count: count
        };
        var query = obj2Str(params);
        if (query) {
            apiUri += '?' + query;
        }
        
        $http.jsonp(apiUri);
    }
]);


myControllers.controller('BookDetailCtrl', [
    '$scope', '$routeParams', '$http',
    function ($scope, $routeParams, $http) {
        var id = parseInt($routeParams.id) || 0;
        var apiUri = 'https://api.douban.com/v2/book/:id?callback=bookDetailCallback';
        __scope = $scope;
        __scope.page = __page;
        $http.jsonp(apiUri.replace(/\:id/, id));
    }
]);


function bookListCallback (data) {
    console.log('bookListCallback', data);
    __scope.books = data.books;
}


function bookDetailCallback (data) {
    console.log('bookDetailCallback', data);
    __scope.book = data;
}


function obj2Str (obj) {
    var arr = [];
    for (var key in obj) {
        arr.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return arr.join('&');
}
